package com.zmn.oms.zmn.aop;

import com.alibaba.fastjson.JSON;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.framework.mq.ZmnMQException;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.dto.OmsBaseOperator;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.dto.OmsStatusOperator;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.track.common.message.WorkStatusMessage;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 类描述：普通单日志记录
 *
 * @author lujia
 * @date 2018/12/04 20:59
 */
@Aspect
@Component
@Order(-1)
public class TrackSyncAspect {

    Logger logger = LoggerFactory.getLogger(TrackSyncAspect.class);

    @Autowired
    ZmnMQSender zmnMQSender;
    @Autowired
    OrderWorkService orderWorkService;

    @Value("${spring.mq.topic.track:''}")
    private String TRACK_TOPIC_TOPIC;
    private static final String TRACK_TOPIC_TAG = "workstatusrealtime";

    /**
     * 设定切入点
     */
    @Pointcut("@annotation(com.zmn.oms.common.annotation.ZsNormalOrderWorkLog)")
    private void pointCutMethod() {
    }

    @Around("pointCutMethod() && @annotation(zsNormalOrderWorkLog)")
    public Object doSync(ProceedingJoinPoint joinPoint, ZsNormalOrderWorkLog zsNormalOrderWorkLog) throws Throwable {
        Object returnValue = joinPoint.proceed();

        try {
            WorkStatusMessage workStatusMessage = new WorkStatusMessage();

            if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
                if (joinPoint.getArgs()[0] instanceof OmsBaseOperator) {
                    OmsBaseOperator omsOperator = (OmsBaseOperator) joinPoint.getArgs()[0];
                    workStatusMessage.setOrderId(omsOperator.getOrderId());
                    workStatusMessage.setWorkId(omsOperator.getWorkId());
                    workStatusMessage.setOperatorLogRemark(omsOperator.getOperatorLogRemark());
                    workStatusMessage.setLogType(zsNormalOrderWorkLog.type());
                    workStatusMessage.setOperator(omsOperator.getOperator());
                    workStatusMessage.setOperatorId(omsOperator.getOperatorId());
                    workStatusMessage.setOperatorType(omsOperator.getOperatorType());
                    workStatusMessage.setEntranceId(omsOperator.getEntranceId());
                } else if (joinPoint.getArgs()[0] instanceof OrderWork) {
                    OrderWork orderWork = (OrderWork) joinPoint.getArgs()[0];
                    workStatusMessage.setOrderId(orderWork.getOrderId());
                    workStatusMessage.setWorkId(orderWork.getWorkId());
                }
            }

            if (Objects.isNull(workStatusMessage.getOrderId()) || Objects.isNull(workStatusMessage.getWorkId())) {
                return returnValue;
            }

            Integer status = null;
            if (joinPoint.getArgs()[0] instanceof OmsStatusOperator) {
                status = ((OmsStatusOperator) joinPoint.getArgs()[0]).getStatus();
            } else {
                OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(workStatusMessage.getOrderId(), workStatusMessage.getWorkId());
                if (Objects.isNull(orderWork)) {
                    return returnValue;
                }
                status = orderWork.getStatus();
            }

            // 设置最新订单状态
            workStatusMessage.setStatus(status);

            String key = String.format("%s-%s", workStatusMessage.getWorkId(), DateUtil.getNowTimestamp());
            String json = JSON.toJSONString(workStatusMessage);

            logger.info("#同步工单状态给跟单系统：key:{}, json:{}", key, json);
            try {
                zmnMQSender.send(TRACK_TOPIC_TOPIC, TRACK_TOPIC_TAG, key, json);
            } catch (ZmnMQException e) {
                logger.error(String.format("同步操作信息给跟单系统失败-MQ[%s]: key=[%s] content=[%s]", workStatusMessage.getWorkId(), key, json), e);
            }

            return returnValue;

        } catch (Exception e) {
            logger.error(String.format("同步操作信息给跟单系统失败-NORMAL: params=[%s]", JSON.toJSONString(joinPoint.getArgs())), e);
        } finally {
            return returnValue;
        }
    }
}
